/**
 * Created by i3-00000 on 2017-3-30.
 */
/**
 * Created by i3-00000 on 2017-3-30.
 */
var express=require('express');
var route=express.Router();
var User=require('../models/user');
//统一数据返回格式
var responseData;
route.use(function(req,res,next) {
   responseData={
      code:0,
      message:'',
   };
   next();
});

//用户注册路由
route.post('/user/register',function(req,res,next){
   var username=req.body.username;
   var password=req.body.password;
   var repassword=req.body.repassword;
   //用户名不能为空
   if(username==''){
      responseData.code=1;
      responseData.message='用户名不能为空';
      //将需要返回的数据返回到前台
      res.json(responseData);
      return;
   }
   //密码不能为空
   if(password==''){
      responseData.code=2;
      responseData.message='密码不能为空';
      res.json(responseData);
      return;
   }
   //两次输入的密码要一致
   if(repassword!==password){
      responseData.code=3;
      responseData.message='输入的密码不一致';
      res.json(responseData);
      return;
   };
   //验证用户名是否已经注册，需要连接数据库
   User.findOne({
      username:username,
   }).then(function(userInfo){
     if(userInfo){
      //表示数据库中有该记录，代表已注册
        responseData.code=4;
        responseData.message='用户名已经被注册了';
        res.json(responseData);
        return;
     }
      else{
        //保存用户注册信息到数据库中
         var user=new User({
            username:username,
            password:password,
         });
        return user.save();
     }
   }).then(function(newuserInfo){
      console.log(newuserInfo);
      responseData.message='注册成功';
      res.json(responseData);
   });
});

//用户登录路由
route.post('/user/login',function(req,res,next){
   var username=req.body.username;
   var password=req.body.password;
   if(username==''){
      responseData.code=1;
      responseData.message='用户名不能为空';
      res.json(responseData);
      return;
   }
   if(password==''){
      responseData.code='2';
      responseData.message='密码不能为空';
      res.json(responseData);
      return;
   }
   User.findOne({
      username:username,
      password:password,
   }).then(function(userInfo){
     if(!userInfo){
        responseData.code='2';
        responseData.message='用户名或密码不正确';
        res.json(responseData);
        return;
     }
      responseData.message='登陆成功';
      responseData.userInfo={
         _id:userInfo._id,
         username:userInfo.username,
         isAdmin:userInfo.isAdmin,
      };
      //将userInfo保存到cookies中转换成字符串发送给浏览器保存，下次请求服务器时，浏览器会一起发送cookies给服务器，userInfo为cookie的名称
      req.cookies.set('userInfo',JSON.stringify({
         _id:userInfo._id,
         username:userInfo.username,
         isAdmin:userInfo.isAdmin,
      }));
      res.json(responseData);
      return;
   });
});

//退出登录
route.get('/user/exit',function(req,res,next){
   req.cookies.set('userInfo',null);
   responseData.code=0;
   res.json(responseData);
   return;
});
module.exports=route;